﻿using System;
using System.Web.Mvc;
using Microsoft.Security.Application;
using MvcForum.Net.Business;
using MvcForum.Net.Enums;
using MvcForum.Net.Mvc;
using MvcForum.Net.Utils;
using Nasa8x.Core;
using Nasa8x.Mvc.Helpers.Attributes;

namespace MvcForum.Net.Controllers
{
    public class MemberController : BaseController
    {
        //
        // GET: /Member/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            //ForumContext.SignOut();
            return View();
        }


        #region UserInfo


        public ActionResult Info(string id)
        {

            string _safeId = AntiXss.HtmlEncode(id);

            var _page = new PageEntity
                            {
                                Name = string.Format(ForumContext.GetText("UserInfo", "PAGE_NAME"), _safeId)
                            };
            ViewData["Page"] = _page;


            var _userInfo = UsersRepository.UserInfo(id);

            if (_userInfo == null)
            {

                TempData["Message"] = string.Format(ForumContext.GetMessage(Messages.UserNotExists), _safeId);

                return View("Message");
            }


            ViewData["UserInfo"] = _userInfo;


            return View("UserInfo");
        }


        #endregion


        #region Active

        public ActionResult Active()
        {

            string _a = Request.QueryString["a"];
            string _email = Request.QueryString["email"];
            if (!string.IsNullOrEmpty(_a) && !string.IsNullOrEmpty(_email))
            {
                var _u = UsersRepository.UserInfo(_a, _email);
                if (_u != null)
                {
                    // UsersRepository.LogIn(_u.UserName, _u.Pwd, true);
                    ForumContext.SetAuthenticationCookie(string.Format("{0};{1}", _u.UserName, _u.Pwd), false);
                    return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.DEFAULT));
                }
            }



            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.ActiveCodeInvalid));
        }

        #endregion


        #region ResetPwd
        public ActionResult ResetPwd()
        {
            
            string _a = Request.QueryString["a"];
            string _email = Request.QueryString["email"];
            if (!string.IsNullOrEmpty(_a) && !string.IsNullOrEmpty(_email))
            {
                var _u = UsersRepository.UserInfo(_a, _email);
                if (_u != null)
                {


                    string _newPwd = RandomPassword.GenerateNumber(6);
                    string _encrypPwd = Encryptor.Password(_u.UserName, _newPwd);

                    // Update New Pwd
                    UsersRepository.ResetPwd(_u.UserId, _encrypPwd);

                    string _changePwdLink = ForumContext.GetAbsoluteUrl(ForumUrls.CHANGE_PASSWORD);

                    string _subject = ForumContext.GetText("LOSTPWD", "SUCCESS_SUBJECT");

                    string _message = string.Format(ForumContext.GetText("LOSTPWD", "SUCCESS_MESSAGE"), _u.UserName, _newPwd, _changePwdLink);


                    // Send Mail new Pwd
                    ForumContext.SendMail(ForumContext.Configuration.ForumEmail, _email, _subject, _message);

                    ForumContext.SignOut();
                    // Auto Login With New Pwd
                    ForumContext.SetAuthenticationCookie(string.Format("{0};{1}", _u.UserName, _encrypPwd), false);

                    return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.DEFAULT));
                }
            }



            return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.ActiveCodeInvalid));
        }

        #endregion


        #region Register

        [HttpPost]
        //[ValidateAntiForgeryToken(Salt = "REGISTER")]
        [IsPostbackFromThisSite]
        public ActionResult Register(FormCollection form)
        {
            bool _susscess = false;
            bool _valid = true;
            string _msg = "";

            string userName = form["username"];
            string pwd = Encryptor.Password(userName, form["pwd"]);

            string email = form["email"];
            double timezone = double.Parse(form["timezone"]);

            string activeCode = "";
            string _returnUrl = "";


            if (ForumContext.NameIsDisallowed(userName))
            {
                _msg = string.Format(ForumContext.GetText("REGISTER", "NAME_IS_DISALLOWED"), userName);
                _valid = false;
            }
            else if (!Nasa8x.Core.Utils.IsEmail(email))
            {
                _msg = ForumContext.GetMessage(Messages.EmailInvalid);
                _valid = false;
            }

            else if (!ForumContext.AllowEmail(email))
            {
                _msg = string.Format(ForumContext.GetText("REGISTER", "EMAIL_NOT_ALLOW"), email);
                _valid = false;
            }
            else if (UsersRepository.UserNameExists(userName))
            {
                _msg = string.Format(ForumContext.GetText("REGISTER", "USERNAME_EXISTS"), userName);
                _valid = false;
            }
            else if (UsersRepository.EmailExists(email))
            {

                _msg = string.Format(ForumContext.GetText("REGISTER", "EMAIL_EXISTS"), email);
                _valid = false;


            }

            string _emailBody, _emailSubject, _activeLink = null;

            if (_valid)
            {

                if (ForumContext.Configuration.RegisterEmailActiveRequired)
                {

                    activeCode = Guid.NewGuid().ToString();
                    _returnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.MESSAGE, Messages.RegisterSuccess);


                    _emailSubject = ForumContext.GetText("REGISTER", "ACTIVE_ACCOUNT");

                    _activeLink = ForumContext.GetAbsoluteUrl(ForumUrls.USER_ACTIVE) + "?email=" +
                                  email + "&a=" + activeCode;


                }
                else
                {
                    _emailSubject = ForumContext.GetText("REGISTER", "REG_SUCCESS");
                    ForumContext.SetAuthenticationCookie(string.Format("{0};{1}", userName, pwd), false);
                    _returnUrl = "/";

                }


                UsersRepository.Register(userName, pwd, email, timezone, activeCode);

                _emailBody = string.Format(ForumContext.GetText("REGISTER", "EMAIL_BODY"), userName, ForumContext.Configuration.ForumName);

                if (!string.IsNullOrEmpty(_activeLink))
                {
                    _emailBody += string.Format(ForumContext.GetText("REGISTER", "ACTIVE_INFO"), _activeLink, _activeLink);
                    // _emailBody += _activeLink;
                }


                ForumContext.SendMail(ForumContext.Configuration.SmtpFrom, email,  _emailSubject, _emailBody);

                _susscess = true;
            }




            return Json(new
                            {
                                success = _susscess,
                                message = _msg,
                                returnUrl = _returnUrl
                            });

        }



        #endregion


        #region LogIn

        [HttpPost]
        //[ValidateAntiForgeryToken(Salt = "LOGIN") ]
        [IsPostbackFromThisSite]
        public ActionResult LogIn(FormCollection form)
        {
            string _username = form["_user"];
            string _pwd = Encryptor.Password(_username, form["_pwd"]);
            bool _autoLogin;// = form["_auto"].ToLower() == "true" ? true : false;

            bool _success = false;
            string _msg = string.Empty;
            string _returnUrl = string.Empty;

           ForumContext.MapBoolean(form["_auto"], out _autoLogin);

            var _user = UsersRepository.LogIn(_username, _pwd, true);

            if (_user != null)
            {

                if (!_user.IsActived)
                {

                    _msg = String.Format(ForumContext.GetMessage(Messages.AccountNoActive),
                                         ForumContext.GetAbsoluteUrl(ForumUrls.REQUEST_ACTIVE_CODE));

                }
                else
                {
                    ForumContext.SetAuthenticationCookie(string.Format("{0};{1}", _username, _pwd), _autoLogin);
                    _success = true;
                    _returnUrl = Server.UrlDecode(form["_returnUrl"]);
                    
                }

            }
            else
            {
                _msg = String.Format(ForumContext.GetMessage(Messages.UserNameOrPwdInvalid),
                                     ForumContext.GetAbsoluteUrl(ForumUrls.LOST_PWD));
            }

            return Json(new
                            {
                                success = _success,
                                message = _msg,
                                reload=string.IsNullOrEmpty(_returnUrl),
                                returnUrl = _returnUrl

                            });
        }

        #endregion

    }


}
